package com.jsgt.greekfire.ui.mine.coindetail.withdraw

import android.Manifest
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.CountDownTimer
import android.text.Editable
import android.text.Html
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.scan.android.CaptureActivity
import com.fhx.core.utils.DialogUtil
import com.fhx.core.utils.PriceFormatUtil
import com.fhx.core.utils.ScreenUtil
import com.fhx.core.utils.ToastUtils
import com.ftd.livepermissions.LivePermissions
import com.ftd.livepermissions.PermissionResult
import com.jsgt.greekfire.R
import com.jsgt.greekfire.ZERO_COMPARE
import com.jsgt.greekfire.bean.CoinBean
import com.jsgt.greekfire.bean.RechargeAddressBean
import com.jsgt.greekfire.bean.UserBean
import com.jsgt.greekfire.event.TransferEvent
import com.jsgt.greekfire.factory.CoinViewModelFactory
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.ui.mine.coindetail.adapter.CoinAdapter
import com.jsgt.greekfire.ui.mine.user.securityset.bindphone.BindPhoneActivity
import com.jsgt.greekfire.ui.mine.coindetail.recharge.rechargerecord.RechargeRecordActivity
import com.jsgt.greekfire.viewmodel.CoinViewModel
import com.jsgt.greekfire.viewmodel.UserViewModel
import com.jsgt.greekfire.common.widget.TabTextView
import kotlinx.android.synthetic.main.activity_withdraw_coin.*
import kotlinx.android.synthetic.main.view_withdraw_coin_layout.*
import org.greenrobot.eventbus.EventBus
import java.math.BigDecimal

/**
 * 提币
 * author fhx
 * create time 2020/4/24 12:28
 **/
class WithdrawActivity : BaseActivity() {
    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }
    private val coinViewModel: CoinViewModel by lazy {
        ViewModelProvider(
            this,
            CoinViewModelFactory()
        ).get(CoinViewModel::class.java)
    }
    private val DECODED_CONTENT_KEY = "codedContent"
    private var balance = 0.0//可用余额
    private var withdraw_charge = 0.0//提币手续费

    companion object {
        private const val REQUEST_CODE = 1002
    }

    private var rechargeAddressBean: RechargeAddressBean? = null
    private var verifyDialog: Dialog? = null
    private var countDown: CountDownTimer? = null

    private var phoneTv: TabTextView? = null
    private var emailTv: TabTextView? = null
    private var sendCodeTv: TextView? = null

    private var pwdEt: EditText? = null
    private var codeEt: EditText? = null
    private var isSendCode = false
    override fun getLayoutId(): Int = R.layout.activity_withdraw_coin
    private val dotNumber = 4
    private var type = 2 //2-USDT  3-GFT
    private var typeStr = "USDT" //"GFT"

    override fun main() {
        title = getString(R.string.coin_withdraw)
        setRightText(getString(R.string.coin_withdraw_record)).setOnClickListener {
            RechargeRecordActivity.start(
                this,
                RechargeRecordActivity.WITHDRAW,
                type
            )
        }

        type = intent.getIntExtra("type", 2)
        if (type == 3) {
            typeStr = "GFT"
            textView99.text = "GFT生态提币地址"
            txv_min.text = "10 $typeStr"
        } else {
            txv_min.text = "10 $typeStr(ERC20)"
        }
        usdt_tv.text = "$typeStr 0"
        valid_sum_tv.text = "到账数量:  0.0 $typeStr"

        num_et.numberDot = dotNumber
        initVerifyDialog()
        val coinAdapter =
            CoinAdapter()
        val coinList = arrayListOf<CoinBean>()
        for (i in 1..6) {
            coinList.add(CoinBean())
        }
        coinAdapter.addData(coinList)
        coin_type_rv.adapter = coinAdapter
        num_et.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (balance < ZERO_COMPARE) {
                    valid_sum_tv.text = "到账数量：0.0 $typeStr"
                    return
                }
                if (!TextUtils.isEmpty(s.toString())) {
                    val num = s.toString().toDouble()
                    if (num >= 10) {
                        if (num > balance) {
                            num_et.setText("${PriceFormatUtil.format(balance, dotNumber)}")
//                            valid_sum_tv.text =
//                                "到账数量：${BigDecimal(balance.toString()).subtract(
//                                    BigDecimal(
//                                        withdraw_charge.toString()
//                                    )
//                                )} $typeStr"
                            num_et.setSelection(num_et.length())
                        } else {
                            valid_sum_tv.text = "到账数量：${BigDecimal(num.toString()).subtract(
                                BigDecimal(
                                    withdraw_charge.toString()
                                )
                            )} $typeStr"
                        }
                    } else {
                        valid_sum_tv.text = "到账数量：0.0 $typeStr"
                    }
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })
        coinAdapter.itemClickListner = {
            coin_withdraw_layout.visibility = View.VISIBLE
            coin_type_rv.visibility = View.GONE
            recommend_tv.visibility = View.GONE
        }

        scan_iv.setOnClickListener {
            LivePermissions(this).request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
            ).observe(this, Observer {
                when (it) {
                    is PermissionResult.Grant -> {
                        startActivityForResult(
                            Intent(this, CaptureActivity::class.java),
                            REQUEST_CODE
                        )
                    }
                    is PermissionResult.Rationale -> {

                    }
                    is PermissionResult.Deny -> {
                        ToastUtils.show(this, "权限拒绝")
                    }
                }
            })
        }
//        coin_choose_tv.setOnClickListener {
//            startActivity(Intent(this, CoinChooseActivity::class.java))
//        }
        all_num_tv.setOnClickListener {
            if (rechargeAddressBean != null && rechargeAddressBean!!.assetBalance != null) {
                num_et.setText(
                    PriceFormatUtil.format(
                        rechargeAddressBean!!.assetBalance!!,
                        dotNumber
                    )
                )
            } else {
                num_et.setText("0")
            }

        }
        submit_tv.setOnClickListener {
            showDialog()
        }
        coinViewModel.rechargeAddress(type.toString())
        coinViewModel.rechargeAddressLiveData.observe(this, Observer {
            balance = it.assetBalance!!
            current_sum_tv.text =
                Html.fromHtml(
                    "当前可提<font color= '#378EEF'>${PriceFormatUtil.format(
                        it.assetBalance!!,
                        dotNumber
                    )}</font> $typeStr"
                )
            rechargeAddressBean = it
        })
        coinViewModel.withdrawCoinLiveData.observe(this, Observer {
            showProgress(false)
            verifyDialog?.dismiss()
            val num = num_et.text.toString()
            ToastUtils.show(this, "提交成功")
            EventBus.getDefault().post(TransferEvent("$num"))
            finish()
        })
        userViewModel.userInfo()
        userViewModel.userInfoLiveData.observe(this, Observer {
            UserBean.instance.mobile = it.mobile
            UserBean.instance.email = it.email
            if (TextUtils.isEmpty(it.mobile) && TextUtils.isEmpty(it.email)) {
                dialog()
            }
        })
        coinViewModel.getManagerCharge("1,2,3")
        coinViewModel.managerChargeLiveData.observe(this, Observer {
            for (i in it) {
                //管理币
//                if (TextUtils.equals("1", i.assetGuid)) {
//                    glb_tv.text = "GFC ${i.price}"
//                }
                //提币手续费
                if (TextUtils.equals(type.toString(), i.assetGuid)) {
                    if (!i.price.isNullOrEmpty() && (i.price == "0.0" || i.price == "0")) {
                        usdt_tv.text = "$typeStr 免费"
                    } else {
                        usdt_tv.text = "$typeStr ${i.price}"
                    }
                    withdraw_charge = i.price!!.toDouble()
                }
            }
        })
        userViewModel.sendSmsLiveData.observe(this, Observer {
            startCountDown()
        })
        userViewModel.sendEmailLiveData.observe(this, Observer {
            startCountDown()
        })
        userViewModel.checkSMSLiveData.observe(this, Observer {
            val pwd = pwdEt?.text.toString().trim()
            showProgress(true)
            submit(pwd)
        })
        userViewModel.checkEmailLiveData.observe(this, Observer {
            val pwd = pwdEt?.text.toString().trim()
            showProgress(true)
            submit(pwd)
        })
        userViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
        })
        coinViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
        })
    }

    private fun startCountDown() {
        isSendCode = true
        ToastUtils.show(this, "已发送")
        sendCodeTv?.isEnabled = false
        countDown = object : CountDownTimer(60000, 1000) {
            override fun onFinish() {
                sendCodeTv?.text = getString(R.string.send_sms_code)
                sendCodeTv?.isEnabled = true
            }

            override fun onTick(millisUntilFinished: Long) {
                sendCodeTv?.text = "${(millisUntilFinished + 500) / 1000}${getString(R.string.second)}"
            }
        }
        countDown?.start()
    }

    /**
     * 验证码/密码窗口
     */
    private fun initVerifyDialog() {
        val contentView = layoutInflater.inflate(R.layout.dialog_withdraw, null, false)
        codeEt = contentView.findViewById(R.id.code_et)
        sendCodeTv = contentView.findViewById(R.id.send_code_tv)
        val submitTv = contentView.findViewById<TextView>(R.id.submit_tv)
        pwdEt = contentView.findViewById(R.id.pwd_et)
        phoneTv = contentView.findViewById(R.id.phone_tv)
        emailTv = contentView.findViewById(R.id.email_tv)
        emailTv?.setOnClickListener {
            emailTv?.setChecked(true)
            phoneTv?.setChecked(false)
        }
        phoneTv?.setOnClickListener {
            phoneTv?.setChecked(true)
            emailTv?.setChecked(false)
        }
        sendCodeTv?.setOnClickListener {
            if (phoneTv!!.mCheck) {
                userViewModel.sendSMS(UserBean.instance.mobile!!)
            } else {
                userViewModel.sendEmail(UserBean.instance.email!!)
            }
        }
        submitTv.setOnClickListener {
            val code = codeEt?.text.toString().trim()
            val pwd = pwdEt?.text.toString().trim()
            if (isSendCode) {

                if (!TextUtils.isEmpty(code)) {
                    if (!TextUtils.isEmpty(pwd)) {
                        showProgress(true)
                        if (phoneTv!!.mCheck) {
                            userViewModel.checkSMSCode(UserBean.instance.mobile!!, code)
                        } else {
                            userViewModel.checkEmailCode(UserBean.instance.email!!, code)
                        }
                    } else {
                        ToastUtils.show(this, "请输入密码")
                    }
                } else {
                    ToastUtils.show(mContext!!, "请输入验证码")
                }
            } else {
                ToastUtils.show(this, "请获取验证码")
            }
        }
        verifyDialog?.setCanceledOnTouchOutside(true)
        verifyDialog = DialogUtil.show(this, contentView, R.style.dialog2)
        val attr = verifyDialog?.window?.attributes
        attr?.width = ScreenUtil.getScreenWidth(this)
        verifyDialog?.window?.setGravity(Gravity.BOTTOM)
        verifyDialog?.window?.setWindowAnimations(R.style.bottomToTopAnim)
    }

    /**
     * 安全设置弹窗
     */
    private fun dialog() {
        val contentView = layoutInflater.inflate(R.layout.dialog_security_set, null, false)
        val dialog = DialogUtil.show(this, contentView)
        contentView.findViewById<TextView>(R.id.bind_tv).setOnClickListener {
            startActivity(Intent(this, BindPhoneActivity::class.java))
            dialog.dismiss()
            finish()
        }
        contentView.findViewById<ImageView>(R.id.close_iv).setOnClickListener {
            dialog.dismiss()
            finish()
        }
        dialog.create()
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
    }

    private fun submit(pwd: String) {
        val blockChainAddress = block_chain_et.text.toString().trim()
        val remark = remark_et.text.toString().trim()
        val num = num_et.text.toString().trim()
        showProgress(true)
        coinViewModel.withdrawCoin(
            if (phoneTv!!.mCheck) 1 else 2,
            blockChainAddress,
            remark,
            type.toString(),
            num,
            pwd
        )
    }

    private fun showDialog() {
        val blockChainAddress = block_chain_et.text.toString().trim()
        val num = num_et.text.toString().trim()
        if (TextUtils.isEmpty(blockChainAddress)) {
            ToastUtils.show(this, "请输入区块链地址")
            return
        }
        if (type == 2 && (!blockChainAddress.startsWith("0x") || blockChainAddress.length != 42)) {
            showToast("提币地址有误")
            return
        }
        if (TextUtils.isEmpty(num)) {
            ToastUtils.show(this, "请输入提币数量")
            return
        }
        if (num.toDouble() < ZERO_COMPARE) {
            ToastUtils.show(this, "提币数量必须大于0")
            return
        }
        if (BigDecimal(10).compareTo(BigDecimal(num)) == 1) {
            ToastUtils.show(this, "提币数量不能小于10")
            return
        }
        if (num.toDouble() > balance) {
            ToastUtils.show(this, "余额不足")
            return
        }
        verifyDialog?.create()
        verifyDialog?.show()
        val bean = UserBean.instance

        if (!TextUtils.isEmpty(bean.email)) {
            emailTv?.visibility = View.VISIBLE
            emailTv?.setChecked(true)
        }

        if (!TextUtils.isEmpty(bean.mobile)) {
            phoneTv?.visibility = View.VISIBLE
            phoneTv?.setChecked(true)
            emailTv?.setChecked(false)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            val content = data?.getStringExtra(DECODED_CONTENT_KEY)
            block_chain_et.setText(content)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        countDown?.cancel()
        countDown = null
    }
}